package org.myspringframework.mvc.processor.impl;

import lombok.extern.slf4j.Slf4j;
import org.myspringframework.mvc.RequestProcessorChain;
import org.myspringframework.mvc.processor.RequestProcessor;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * org.myspringframework.mvc.processor.impl <br>
 * 精通资源请求处理，包括但不限于图片、css、以及js文件等
 *
 * @author jaymin
 * @since 2021/5/22
 */
@Slf4j
public class StaticResourceRequestProcessor implements RequestProcessor {

    private static final String DEFAULT_TOMCAT_SERVLET = "default";

    private static final String STATIC_RESOURCE_PREFIX = "/static/";

    private RequestDispatcher requestDispatcher;

    public StaticResourceRequestProcessor(ServletContext servletContext) {
        this.requestDispatcher = servletContext.getNamedDispatcher(DEFAULT_TOMCAT_SERVLET);
        if (Objects.isNull(this.requestDispatcher)) {
            throw new RuntimeException("there is no default tomcat servlet.");
        }
        log.info("the default servlet for static resource is {}", DEFAULT_TOMCAT_SERVLET);
    }

    @Override
    public boolean proceed(RequestProcessorChain requestProcessorChain) throws Exception {
        String requestPath = requestProcessorChain.getRequestPath();
        HttpServletRequest httpServletRequest = requestProcessorChain.getHttpServletRequest();
        HttpServletResponse httpServletResponse = requestProcessorChain.getHttpServletResponse();
        if (isStaticResource(requestPath)) {
            requestDispatcher.forward(httpServletRequest, httpServletResponse);
            return false;
        }
        return true;
    }

    public boolean isStaticResource(String requestPath) {
        return requestPath.startsWith(STATIC_RESOURCE_PREFIX);
    }
}
